Ext.define('TD.controller.task.EditController', {
    extend: 'Ext.app.Controller',

    stores: [
        'TaskStore'
    ],
    
    models: [
        'Task'
    ],
    
    views: [
        'task.EditView'
    ],

    init: function() {
        this.control({
        	'taskedit button[action=save]': {
                click: this.updateTask
            }
        });
    },
    
    updateTask : function(button) {
        var win = button.up('window');
        var form = win.down('form');
        
        var record = form.getRecord();
        var values = form.getValues();

        // TODO js validation
        
        // Create new
        if (record == null) {
           Ext.Ajax.request({
               url: 'task/create.json',
               params: {
                   record: Ext.encode(values)
               },
               // Server create success
               success: function(response){
                   var id = Ext.decode(response.responseText);
                   values.id = id;
                   
                   var task = Ext.create('TD.model.Task', values);
                   Ext.widget('tasklist').getStore().add(task);
               }
           });
        } else {
            // update existed
            Ext.Ajax.request({
                url: 'task/update.json',
                params: {
                    record: Ext.encode(values)
                },
                // Server update success
                success: function(response){
                    record.set(values);
                }
            });
        }
    	
    	win.close();
    }
});